package com.weiyuwqj.admin.controller.admin.asset;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.net.URL;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import com.weiyuwqj.admin.controller.base.BaseController;
import com.weiyuwqj.api.constant.Message;
import com.weiyuwqj.api.exception.CrowdException;
import com.weiyuwqj.api.model.SysAssetPicture;
import com.weiyuwqj.api.model.SysAssetProduct;
import com.weiyuwqj.api.service.SysAssetPictureService;
import com.weiyuwqj.api.service.SysAssetProductService;
import com.weiyuwqj.api.tool.QiniuUpload;
import com.weiyuwqj.api.util.ImageUtil;
import com.weiyuwqj.api.util.IpUtils;
import com.weiyuwqj.api.util.StringUtils;

/**
 * @author cx
 * @className:SysAssetCompanyController
 * @Description: 产品图片controller
 * @date:2017年3月25日上午11:27:40
 */
@RestController
@RequestMapping(value = "/admin/assetPicture")
public class SysAssetPictureController extends BaseController {

    @Autowired
    private SysAssetPictureService sysAssetPictureService;
    @Autowired
    private SysAssetProductService sysAssetProductService;

    /**
     * 列表
     *
     * @param productId 产品id
     * @return
     */
    @RequestMapping(value = "/getList", method = RequestMethod.POST)
    public List<SysAssetPicture> getList(final Integer productId) {
        return this.sysAssetPictureService.getList(productId);
    }

    /**
     * 根据id查询
     *
     * @param id
     * @return
     */
    @RequestMapping(value = "/findById", method = RequestMethod.POST)
    public SysAssetPicture findById(final Integer id) {
        return this.sysAssetPictureService.findById(id);
    }

    /**
     * 保存图片
     *
     * @param sysAssetPicture
     * @return
     */
    @RequestMapping(value = "/add", method = RequestMethod.POST)
    public HashMap<String, String> add(final SysAssetPicture sysAssetPicture) {
        final SysAssetProduct assetProduct = this.sysAssetProductService.findById(sysAssetPicture.getProductId());
        if (assetProduct == null) {
            throw new CrowdException("sys.asset.product.not_exists");
        }
        sysAssetPicture.setUpdateUrl(sysAssetPicture.getUrl());
        sysAssetPicture.setCreator(getSessionUserId());
        sysAssetPicture.setAddip(IpUtils.get());
        sysAssetPicture.setAddtime(new Date());
        if (sysAssetPicture.getId() != null && sysAssetPicture.getId() >= 0) {
            this.sysAssetPictureService.updateNotNull(sysAssetPicture);
        } else {
            this.sysAssetPictureService.save(sysAssetPicture);
        }
        return Message.OK;
    }


    /**
     * 删除
     *
     * @param id 图片id
     * @return
     */
    @RequestMapping(value = "/delete", method = RequestMethod.POST)
    public HashMap<String, String> delete(final Integer id) {
        this.sysAssetPictureService.delete(id);
        return Message.OK;
    }

    /**
     * 重置图片路径
     *
     * @param id
     * @return
     */
    @RequestMapping(value = "/reset", method = RequestMethod.POST)
    public HashMap<String, String> reset(final Integer id) {
        final SysAssetPicture sysAssetPicture = this.findById(id);
        if (sysAssetPicture == null) {
            throw new CrowdException("sys.asset.picture.id.not_exists");
        }
        if (StringUtils.isNull(sysAssetPicture.getUrl())) {
            throw new CrowdException("sys.asset.picture.url.not_exists");
        }
        sysAssetPicture.setUpdateUrl(sysAssetPicture.getUrl());
        this.sysAssetPictureService.updateNotNull(sysAssetPicture);
        final HashMap<String, String> map = new HashMap<String, String>();
        map.put("result", "success");
        map.put("url", sysAssetPicture.getUpdateUrl());
        return map;
    }

    /**
     * 处理图片
     *
     * @param id          图片id
     * @param type        1水印  2模糊
     * @param x轴
     * @param y轴
     * @param screenshotX 图片的宽
     * @param screenshotY 图片的高
     * @return
     */
    @SuppressWarnings("deprecation")
    @RequestMapping(value = "/dealPicture")
    public HashMap<String, String> dealPicture(final Integer id, final Integer type, final Integer x, final Integer y,
                                               Integer screenshotX, Integer screenshotY) {
        final SysAssetPicture sysAssetPicture = this.findById(id);
        if (sysAssetPicture == null) {
            throw new CrowdException("sys.asset.picture.id.not_exists");
        }
        if (StringUtils.isNull(sysAssetPicture.getUpdateUrl())) {
            throw new CrowdException("sys.asset.picture.id.not_exists");
        }
        final String picUrl = sysAssetPicture.getUpdateUrl();
        String targetUrl = ((ServletRequestAttributes) RequestContextHolder.currentRequestAttributes()).getRequest()
                .getRealPath("/") + "/picture/asset/upload/";
        File file = new File(targetUrl);
        if (!file.exists()) {
            file.mkdirs();
        }
        String fileName = System.currentTimeMillis() + ".jpg";
        String targetUrlFile = targetUrl + fileName;
        try {
            URL url = new URL(picUrl);
            BufferedInputStream bis = new BufferedInputStream(url.openStream());
            OutputStream bos = new FileOutputStream(new File(targetUrlFile));
            byte[] bytes = new byte[1024];
            int len;
            while ((len = bis.read(bytes)) > 0) {
                bos.write(bytes, 0, len);
            }
            bis.close();
            bos.flush();
            bos.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        String pressImg = "http://onlyvy1nf.bkt.clouddn.com/shuiyin.png";
//        if (type == 2) {
//            pressImg = "http://onlyvy1nf.bkt.clouddn.com/ma.jpg";
//        }
        if (screenshotX == null) {
            screenshotX = 0;
        }
        if (screenshotY == null) {
            screenshotY = 0;
        }
        if (type == 1) {
            //加水印
            ImageUtil.pressImage(pressImg, targetUrlFile, x, y, screenshotX, screenshotY, type);
        } else {
           //马赛克
            ImageUtil.mosaic(targetUrlFile, x, y, screenshotX, screenshotY);
        }
        String uploadUrl = QiniuUpload.uploadQiniu(targetUrlFile, "/picture/asset/upload/" + fileName);
        sysAssetPicture.setUpdateUrl(uploadUrl);
        this.sysAssetPictureService.updateAll(sysAssetPicture);
        final HashMap<String, String> map = new HashMap<String, String>();
        map.put("result", "success");
        map.put("url", uploadUrl);
        return map;
    }

}
